package day20180530;

import java.nio.ByteBuffer;

public class testdump {

    public static void main(String[] args){
        directMemoryAllocate();
        memoryRW();

    }

    /**
     * 内存分配耗时。
     * direct:直接的
     */
    public static void directMemoryAllocate(){
        long starttime=System.currentTimeMillis();
        for (int i=0;i<1000000;i++){
            ByteBuffer byteBuffer=ByteBuffer.allocate(400);
        }
        System.out.println("堆内存"+(System.currentTimeMillis()-starttime));

        long starttime2=System.currentTimeMillis();
        for (int i=0;i<1000000;i++){
            ByteBuffer byteBuffer=ByteBuffer.allocateDirect(400);
        }
        System.out.println("直接内存"+(System.currentTimeMillis()-starttime2));
    }

    public static void memoryRW() {
        ByteBuffer buffer = ByteBuffer.allocateDirect(400);
        ByteBuffer buffer2 = ByteBuffer.allocate(400);
        long tsStart = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            for (int j = 0; j < 100; j++) {
                buffer.putInt(j);
            }
            buffer.flip();
            for (byte j = 0; j < 100; j++) {
                buffer.getInt();
            }
            buffer.clear();
        }
        System.out.println("direct memory rw： " + (System.currentTimeMillis() - tsStart) + " ms");
        tsStart = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            for (int j = 0; j < 100; j++) {
                buffer2.putInt(j);
            }
            buffer2.flip();
            for (byte j = 0; j < 100; j++) {
                buffer2.getInt();
            }
            buffer2.clear();
        }
        System.out.println("heap memory rw： " + (System.currentTimeMillis() - tsStart) + " ms");
    }
}
